<template>
  <el-drawer
    v-model="open"
    title="课次详情"
    :with-header="true"
    size="90%"
    class="roll-call-make-drawer"
    :close-on-click-modal="false"
    :before-close="closeW"
  >
    <el-space fill wrap direction="horizontal" style="width: 100%">
      <el-card shadow="never">
        <div style="font-size: 24px; margin-bottom: 30px">
          <el-row :gutter="10" class="mb8">
            <el-col :span="24">
              {{ form.className }}
            </el-col>
          </el-row>
        </div>
        <el-form ref="csRef" :model="form" label-width="auto">
          <el-row :gutter="10" class="mb8">
            <el-col :span="24">
              <el-form-item label="授课课程" prop="courseId">
                <el-select
                  style="width: 320px"
                  v-model="form.courseId"
                  placeholder="课程"
                  clearable
                  disabled
                >
                  <el-option
                    v-for="item in courseList"
                    :key="item.id"
                    :label="
                      item.state === '1' ? item.name + '(已停用)' : item.name
                    "
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="上课日期"
                prop="classDate"
                :rules="[
                  {
                    required: true,
                    message: '请选择上课日期',
                    trigger: 'change',
                  },
                ]"
              >
                <el-date-picker
                  style="width: 320px"
                  v-model="form.classDate"
                  class="mr-4"
                  placeholder="上课日期"
                  value-format="YYYY-MM-DD HH:mm:ss"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="上课时间"
                prop="classStartTime"
                :rules="[
                  {
                    required: true,
                    message: '请选择上课时间',
                    trigger: 'change',
                  },
                ]"
              >
                <el-time-select
                  style="width: 140px"
                  v-model="form.classStartTime"
                  :max-time="form.classEndTime"
                  class="mr-4"
                  placeholder="开始时间"
                  start="00:00"
                  step="00:05"
                  end="23:55"
                />

                <div
                  style="text-align: center; width: 40px; display: inline-block"
                >
                  ~
                </div>
                <el-time-select
                  style="width: 140px"
                  v-model="form.classEndTime"
                  :min-time="form.classStartTime"
                  placeholder="结束时间"
                  start="00:00"
                  step="00:05"
                  end="23:55"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="主班老师"
                prop="teacher"
                :rules="[
                  {
                    required: true,
                    message: '请选择主班老师',
                    trigger: 'change',
                  },
                ]"
              >
                <el-select
                  style="width: 320px"
                  v-model="form.teacher"
                  placeholder="主班老师"
                  clearable
                >
                  <el-option
                    v-for="item in teacherList"
                    :key="item.value"
                    :label="
                      !item.isJob
                        ? item.label + '(已离职)'
                        : !item.isTeacher
                        ? item.label + '(非授课)'
                        : item.label
                    "
                    :value="item.value"
                    :disabled="!item.isJob || !item.isTeacher"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="助教老师" prop="assistantArr">
                <el-select
                  style="width: 320px"
                  v-model="form.assistantArr"
                  placeholder="助教老师"
                  multiple
                  clearable
                >
                  <el-option
                    v-for="item in teacherList"
                    :key="item.value"
                    :label="
                      !item.isJob
                        ? item.label + '(已离职)'
                        : !item.isTeacher
                        ? item.label + '(非授课)'
                        : item.label
                    "
                    :value="item.value"
                    :disabled="!item.isJob || !item.isTeacher"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="授课课时"
                prop="classHour"
                :rules="[
                  {
                    required: true,
                    message: '请填写授课课时',
                    trigger: 'blur',
                  },
                ]"
              >
                <el-input-number
                  v-model="form.classHour"
                  :min="0"
                  @change="handleClassHourChange"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="上课教室" prop="classRoom">
                <el-select
                  style="width: 320px"
                  v-model="form.classRoom"
                  placeholder="上课教室"
                  clearable
                >
                  <el-option
                    v-for="item in roomList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="上课内容" prop="description">
                <el-input
                  type="textarea"
                  v-model="form.description"
                  placeholder="请输入上课内容"
                  style="width: 500px"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-card>
      <el-switch
        v-model="immediately"
        :active-value="0"
        :inactive-value="1"
        active-text="立即点名"
        v-if="$props.from === 'openclass'"
      />
      <el-card shadow="never" v-if="immediately === 0">
        <el-row :gutter="10" class="mb8">
          <el-col :span="12">
            <el-button
              type="primary"
              plain
              @click="handleAddTemp"
              v-if="$props.from !== 'openclass'"
            >
              添加临时学员
            </el-button>

            <el-button
              type="primary"
              plain
              @click="handleAddMakeup"
              v-if="$props.from === 'overtime'"
            >
              添加补课学员
            </el-button>
          </el-col>
        </el-row>
        <el-alert
          title="【温馨提示】“添加临时学员”、“添加补课学员”和“移出课次”均是实时操作，请谨慎处理；另上述操作将会引起学员列表的刷新，请优先完成上述操作后再做数据填写工作，避免列表刷新造成填写数据的丢失和重填。"
          type="warning"
          :closable="false"
        />
        <el-table v-loading="loading" :data="memberList" border>
          <el-table-column label="学员姓名" align="center" prop="studentName">
            <template #default="scope">
              {{
                scope.row.studentName +
                (scope.row.temp === 0
                  ? "(临时学员)"
                  : scope.row.temp === 2
                  ? "(补课学员)"
                  : scope.row.temp === 3
                  ? "(试听学员)"
                  : "")
              }}
            </template>
          </el-table-column>
          <el-table-column label="手机号" align="center" prop="mobile" />
          <el-table-column label="授课课程" align="center" prop="courseNameC" />
          <el-table-column label="消耗方式" align="center" prop="courseName" />
          <el-table-column label="剩余额度" align="center" prop="num">
            <template #default="scope">{{ scope.row.num + "课时" }}</template>
          </el-table-column>
          <el-table-column
            label="到课状态"
            align="center"
            prop="state"
            width="300"
          >
            <template #default="scope">
              <el-form-item :prop="`memberList.${scope.$index}.state`">
                <el-button-group v-model="scope.row.state">
                  <el-button
                    :class="{ selected: scope.row.state === '2' }"
                    value="2"
                    @click="
                      scope.row.state = '2';
                      if (scope.row.temp !== 3)
                        scope.row.classHourPay = form.classHour;
                      calculateNumList();
                    "
                    >到课</el-button
                  >
                  <el-button
                    :class="{ selected: scope.row.state === '3' }"
                    value="3"
                    @click="
                      scope.row.state = '3';
                      if (scope.row.temp !== 3)
                        scope.row.classHourPay = form.classHour;
                      calculateNumList();
                    "
                    >迟到</el-button
                  >
                  <el-button
                    :class="{ selected: scope.row.state === '4' }"
                    value="4"
                    @click="
                      scope.row.state = '4';
                      scope.row.classHourPay = 0;
                      calculateNumList();
                    "
                    >请假</el-button
                  >
                  <el-button
                    :class="{ selected: scope.row.state === '5' }"
                    value="5"
                    @click="
                      scope.row.state = '5';
                      scope.row.classHourPay = 0;
                      calculateNumList();
                    "
                    >未到</el-button
                  >
                </el-button-group>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="扣除额度" align="center" prop="classHourPay">
            <template #default="scope">
              <el-form-item :prop="`memberList.${scope.$index}.classHourPay`">
                <el-input
                  v-model="scope.row.classHourPay"
                  @input="
                    (value) =>
                      (scope.row.classHourPay = Number(
                        value.replace(/[^\d]/g, '')
                      ))
                  "
                  :disabled="scope.row.temp === 3"
                ></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column
            label="备注"
            align="center"
            prop="remark"
            width="260"
          >
            <template #default="scope">
              <el-form-item :prop="`memberList.${scope.$index}.remark`">
                <el-input
                  v-model="scope.row.remark"
                  type="textarea"
                  :rows="1"
                ></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            align="center"
            width="80"
            class-name="small-padding fixed-width"
          >
            <template #default="scope">
              <el-button link type="primary" @click="handleDelete(scope.row)">
                移出课次
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>

      <el-card shadow="never" v-if="immediately === 1">
        <el-table v-loading="loading" :data="memberList2" border>
          <el-table-column label="学员姓名" align="center" prop="studentName">
            <template #default="scope">
              {{
                scope.row.studentName +
                (scope.row.temp === 0
                  ? "(临时学员)"
                  : scope.row.temp === 2
                  ? "(补课学员)"
                  : scope.row.temp === 3
                  ? "(试听学员)"
                  : "")
              }}
            </template>
          </el-table-column>
          <el-table-column label="手机号" align="center" prop="mobile" />
          <el-table-column label="消耗方式" align="center" prop="courseName" />
          <el-table-column label="剩余额度" align="center" prop="num">
            <template #default="scope">{{ scope.row.num + "课时" }}</template>
          </el-table-column>
          <el-table-column
            label="到课状态"
            align="center"
            prop="state"
            v-if="!props.ifEdit"
          >
            <template #default="scope">{{
              {
                "1": "未开课",
                "2": "到课",
                "3": "迟到",
                "4": "请假",
                "5": "未到",
              }[scope.row.state]
            }}</template>
          </el-table-column>
          <!-- <el-table-column label="补课状态" align="center" prop="" /> -->
          <el-table-column
            label="扣除额度"
            align="center"
            prop="classHourPay"
          />
          <el-table-column
            label="备注"
            align="center"
            prop="remark"
            width="350"
          />
          <el-table-column
            label="操作"
            align="center"
            width="80"
            class-name="small-padding fixed-width"
          >
            <template #default="scope">
              <el-button link type="primary" @click="handleDelete(scope.row)">
                移出课次
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </el-space>
    <template #footer>
      <span class="num-style">{{
        "到课" +
        numList[0] +
        "人  迟到" +
        numList[1] +
        "人  请假" +
        numList[2] +
        "人  未到" +
        numList[3] +
        "人"
      }}</span>
      <el-button @click="closeW">取消</el-button>
      <el-button type="primary" :loading="loading" @click="submitForm">
        {{
          props.from === "openclass"
            ? loading
              ? "开班补课中..."
              : "完成开班补课"
            : loading
            ? "点名中..."
            : "完成点名"
        }}
      </el-button>
    </template>
  </el-drawer>
  <MemberSelector
    ref="mSelector"
    v-bind="$props"
    @refreshPage="getMumberListByLesson"
    from="rollCall"
    :data="form"
    title="添加临时学员"
  />
  <MemberMakeupSelector
    ref="muSelector"
    v-bind="$props"
    :data="form"
    @refreshPage="getMumberListByLesson"
  />
</template>

<script setup>
import MemberSelector from "./memberSelector.vue";
import MemberMakeupSelector from "./memberMakeupSelector.vue";
import { getTLabelListAPI } from "@/api/registrar/classroom";
import {
  getRollCallDetailAPI,
  getMumberListByRollCallIdAPI,
  getClassListAPI,
  deleteOrderInRollCallAPI,
  updateBatchOrderAPI,
  updateOrderInRollCallAPI,
  updateOpenClassAPI,
} from "@/api/registrar/class";

import { getPeopleList } from "@/api/studentManagement/index";
import { getCourseListAPI } from "@/api/registrar/course";
const props = defineProps({
  from: {
    type: String,
    default: "rollcall", // 区分页面不同：rollcall：班级点名情况；overtime:上课记录里的超时未点点名；openclass:开班补课使用
  },
  courseFilterIds: {
    type: String,
  },
  isVip: {
    type: String,
  },
  classId: {
    type: String,
  },
});

const { proxy } = getCurrentInstance();
const emits = defineEmits(["refreshPage"]);
const loading = ref(false);
const open = ref(false);
const mSelector = ref(null);
const muSelector = ref(null);

const data = reactive({
  form: {},
  currentItem: {},
  memberList: [],
  memberList2: [], // 仅存储，不改变state,开班补课不立即点名时使用
  numList: [0, 0, 0, 0], // 到课、迟到、请假、未到的个数
});

const { form, currentItem, memberList, memberList2, numList } = toRefs(data);

const roomList = ref([]);
const teacherList = ref([]);
const courseList = ref([]);
const classList = ref([]);

const immediately = ref(0); // 是否立即点名

// 监听------------------------------------------------------------------------------------------------------------
watch(
  () => form.value.assistantArr,
  (n, o) => {
    if (!n) n = [];
    form.value.assistant = n.join(",");
  }
);

// 事件------------------------------------------------------------------------------------------------------------------
// 移出课次
function handleDelete(row) {
  if (memberList.value.length === 1) {
    proxy.$modal.msgError("至少有一个学员");
    return;
  }
  if (props.from === "openclass") {
    memberList.value = memberList.value.filter((member) => {
      return member.id !== row.id;
    });
    memberList2.value = memberList2.value.filter((member) => {
      return member.id !== row.id;
    });
  } else {
    deleteOrderInRollCallAPI({
      id: row.id,
    }).then(() => {
      getMumberListByLesson();
    });
  }
}

function handleClassHourChange(value) {
  memberList.value.forEach((element) => {
    if (element.state === "2" || element.state === "3") {
      if (element.temp === 3) element.classHourPay = 0;
      else element.classHourPay = form.value.classHour;
    } else if (element.state === "4" || element.state === "5") {
      element.classHourPay = 0;
    }
  });
}

function updateBatchOrder() {
  if (memberList.value.length === 0) {
    proxy.$modal.msgError("学员不可为空");
    return;
  }
  loading.value = true;
  updateBatchOrderAPI(memberList.value)
    .then((response) => {
      loading.value = false;
      if (response.msg === "E103") {
        proxy.$modal.msgError("请将剩余额度为0的学员移出课次后再点名");
        return;
      }
      updateOrderInRollCall();
    })
    .catch(() => {
      loading.value = false;
    });
}

function updateOrderInRollCall() {
  loading.value = true;
  updateOrderInRollCallAPI(form.value).then((response) => {
    loading.value = false;
    proxy.$modal.msgSuccess("已完成点名");
    closeW();
    refreshParent();
  });
}

function updateOpenClass() {
  if (memberList.value.length === 0) {
    proxy.$modal.msgError("学员不可为空");
    return;
  }
  if (immediately.value === 0) form.value.tCourseOrders = memberList.value;
  else form.value.tCourseOrders = memberList2.value;

  loading.value = true;

  form.value.immediately = immediately.value; // 立即点名，0是1否
  updateOpenClassAPI(form.value)
    .then((response) => {
      proxy.$modal.msgSuccess("已完成开班补课");
      loading.value = false;
      closeW();
      refreshParent();
    })
    .catch(() => {
      loading.value = false;
    });
}

function submitForm() {
  proxy.$refs["csRef"].validate((valid) => {
    if (valid) {
      if (props.from === "openclass") {
        updateOpenClass();
      } else {
        updateBatchOrder();
      }
    } else {
      proxy.$modal.msgError("表单校验未通过，请重新检查提交内容");
    }
  });
}

function closeW() {
  open.value = false;
  form.value = {};
  proxy.resetForm("csRef");
}

// function addMumber(addList) {
//   addList.forEach((element) => {
//     element.studentName = element.name;
//     element.temp=0
//   });
//   memberList.value = [...memberList.value, ...addList];
// }
// 方法-------------------------------------------------------------------------------------------------------------------

function getCourseList() {
  loading.value = true;
  getCourseListAPI({
    pageSize: 9999,
    pageNum: 1,
    state: "0",
  }).then((response) => {
    courseList.value = response.rows;
    loading.value = false;
  });
}

// 教室
function getRoomList() {
  loading.value = true;
  getTLabelListAPI({ lableType: "class_room" }).then((response) => {
    roomList.value = response.data;
    loading.value = false;
  });
}

// 班级
function getClassList() {
  loading.value = true;
  getClassListAPI({ pageSize: 9999, pageNum: 1, isVip: props.isVip }).then(
    (response) => {
      classList.value = response.rows;
      loading.value = false;
    }
  );
}

// 获取教师列表
function getTeacherList() {
  loading.value = true;
  getPeopleList({ isTeach: 1 }).then((response) => {
    teacherList.value = response.data;
    loading.value = false;
  });
}

function initPicker() {
  getCourseList();
  getRoomList();
  getClassList();
  getTeacherList();
}

function initPage() {
  if (props.from === "openclass") {
    form.value = {
      courseId: currentItem.value.courseId,
      classHour: currentItem.value.classHour,
      classId: props.classId,
    };
    // studentList按照原memberList的格式拼写组合
    memberList.value = JSON.parse(
      JSON.stringify(currentItem.value.studentList)
    );
    memberList2.value = JSON.parse(
      JSON.stringify(currentItem.value.studentList)
    );
    memberList.value.forEach((element) => {
      element.tempOrderNo = element.orderNo;
      element.state = "2";
      if (element.temp === 3) element.classHourPay = 0;
      else element.classHourPay = form.value.classHour;
      element.temp = 2;
      element.remark =
        "原缺课课次：" + element.classDate + " " + element.className;
    });

    memberList2.value.forEach((element) => {
      element.tempOrderNo = element.orderNo;
      element.state = "1";
      element.classHourPay = 0;
      element.temp = 2;
      element.remark =
        "原缺课课次：" + element.classDate + " " + element.className;
    });

    calculateNumList();
  } else {
    getDetail();
  }
}

function handleOpen(item) {
  open.value = true;
  currentItem.value = JSON.parse(JSON.stringify(item));
  initPicker();
  initPage();
}

function getDetail() {
  getRollCallDetailAPI({ id: currentItem.value.id }).then((response) => {
    form.value = response.data;
    form.value.courseId = form.value.courseId.toString();
    form.value.classId = form.value.classId.toString();
    form.value.classRoom = form.value.classRoom
      ? parseInt(form.value.classRoom)
      : null;
    form.value.range = [form.value.startTime, form.value.endTime];
    getMumberListByLesson();
  });
}

// 查询每节课次里的学员信息
function getMumberListByLesson() {
  getMumberListByRollCallIdAPI({
    orderNo: currentItem.value.orderNo,
    pageSize: 9999,
    pageNum: 1,
  }).then((response) => {
    memberList.value = response.rows;
    memberList.value.forEach((element) => {
      if (element.state === "1") {
        element.state = "2";
        if (element.temp === 3) element.classHourPay = 0;
        else element.classHourPay = form.value.classHour;
      }
    });
    calculateNumList();
  });
}

function calculateNumList() {
  numList.value = [0, 0, 0, 0];
  memberList.value.forEach((element) => {
    if (element.state === "2") {
      numList.value[0]++;
    } else if (element.state === "3") {
      numList.value[1]++;
    } else if (element.state === "4") {
      numList.value[2]++;
    } else if (element.state === "5") {
      numList.value[3]++;
    }
  });
}

// 某课次添加临时学员
function handleAddTemp() {
  mSelector.value.openSelector();
}

// 某课次添加补课学员
function handleAddMakeup() {
  muSelector.value.openSelector();
}

function refreshParent() {
  emits("refreshPage");
}

defineExpose({ handleOpen }); // 用于父组件调用
</script>

<style lang="scss" scoped>
.selected {
  background-color: rgb(235, 245, 255); /* 设置选中时的背景色 */
  color: rgb(64, 158, 255); /* 设置选中时的文字颜色 */
  border-color: rgb(159, 206, 255);
}
.num-style {
  color: #666;
  font-size: 14px;
  display: inline-block;
  margin-right: 20px;
}
</style>

<style scoped lang="scss">
.el-table__row .el-form-item {
  margin: 0;
}
</style>
